<?php
/**
 * Created by PhpStorm.
 * Script Name: CheckAuth.php
 * Create: 2022/9/19 19:15
 * Description:
 * Author: fudaoji<fdj@kuryun.cn>
 */

namespace plugin\wechat\app\admin\middleware;

use app\common\service\App;
use support\View;
use Webman\Http\Request;
use Webman\Http\Response;
use Webman\MiddlewareInterface;

class CheckAuth implements MiddlewareInterface
{
    /**
     * @inheritDoc
     */
    public function process(Request $request, callable $handler): Response
    {
        $app        = request()->getApp();
        $controller = request()->getController();
        $action     = request()->getAction();

        //如果想继承框架后台的角色权限系统，则使用以下逻辑
        if(! $admin_info = request()->session()->get(SESSION_ADMIN)){
            //说明不是创始人
            $admin_info = [];  //这边自行处理员工数据获取
        }else{
            //说明是创始人
            $admin_info['super'] = 1;
        }
        if (empty($admin_info)) {
            if($controller !== 'auth'){
                return redirect('/admin/auth/login');
            }
        }else{
            $auth_check = true;  //todo 根据实际情况判断权限
            if(! $auth_check){
                $res = ['code' => 0, 'msg' => dao_trans('暂无权限')];
                return \request()->isAjax() ? json($res) :
                    \view(config('app.dispatch_error'), $res);
            }
        }

        $controller_layer = explode('/', $controller);
        $controller = $controller_layer[count($controller_layer) - 1];
        View::assign('app', $app);
        View::assign('controller', $controller);
        View::assign('action', $action);
        View::assign('admin', $admin_info);
        View::assign('current_menu', $controller . DIRECTORY_SEPARATOR . $action);
        View::assign('menus', plugin_config('menu'));
        View::assign('app_info', App::getApp(\request()->plugin));
        return $handler($request);
    }
}